<template>
	<view class="mbti-groups">
		<mBack ref="mBack" @getGameResult="handleBack"></mBack>
		<view class="mbti-groups-content flex-column-start-center" :style="{'background-image': `url(${bgUrl})`}">
			<view class="top-box" :style="{height:capsuleBottomTop+'rpx'}"></view>
			<view class="content-box">
				<scroll-view ref="scrollView" :scroll-y="true" class="scroll-content" :show-scrollbar="false"
					:scroll-with-animation="true">
					<view class="discover-top-box" style="width: 100%;height: 98rpx;"></view>
					<view class="discover-box flex-column-start-center">
						<view class="tip-title">添加你的Clackey
							<view class="change-add-type" @click="handleChangeAddType">
								<text v-if="!isAddOldDevice">添加旧设备</text>
								<text v-else>添加新设备</text>
							</view>
						</view>

						<view class="tip-sub-title last-sub-title" v-if="!isAddOldDevice">
							请确认你的Clackey处于开机状态。
						</view>
						<view class="tip-sub-title flex-row-start-center" v-if="isAddOldDevice">
							长按电源键 <image class="switch-icon"
								src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/4722c60c92994455b29f6ae05dd3030d.png"
								mode="aspectFill"></image>，重启你的Clackey
						</view>
						<view class="tip-sub-title last-sub-title" v-if="isAddOldDevice">
							快速按一下主按钮，进入配网模式
						</view>

						<view class="discover-blue-searching flex-column-start-center">
							<view class="discover-blue-icon flex-row-center-center">
								<view class="discover-blue-center flex-row-center-center">
									<view class="discover-blue-center-content flex-row-center-center">
										<image class="discover-blue-center-icon"
											src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/23cca55db59043e6b00c9cf6cad0db06.png"
											mode="aspectFill"></image>
									</view>
									<view class="blue-child"></view>
									<view class="blue-child blue-child-two"></view>
									<view class="blue-child blue-child-three"></view>

								</view>
							</view>
							<view class="discover-blue-tip">搜索中...</view>
						</view>
						<view class="device-list-box" :style="{opacity:nowDeviceList.length?1:0}">
							<view class="device-list-tip">发现可连接的Clackey</view>
							<view class="device-list">
								<!-- 		<scroll-view ref="scrollView" :scroll-y="true" class="scroll-content"
										:show-scrollbar="false" :scroll-with-animation="true">
										<view class="device-list-content">
											<view class="device-item flex-row-start-center"
												v-for="(item,index) in nowDeviceList" :key="index"
												@click="handleNewDeviceClick(item,index)">
									
												<view class="device-avatar flex-row-center-center">
													<image class="cover-img" :src="item.mbtiAvatar" mode="aspectFill"></image>
												</view>
												<view class="device-name flex-row-start-center">{{item.name}}</view>
									
											</view>
									
										</view>
									</scroll-view> -->
								<view class="device-list-content">
									<view class="device-item flex-row-start-center"
										v-for="(item,index) in nowDeviceList" :key="index"
										@click="handleNewDeviceClick(item,index)">

										<view class="device-avatar flex-row-center-center">
											<image class="cover-img" :src="item.mbtiAvatar" mode="aspectFill"></image>
										</view>
										<view class="device-name flex-row-start-center">{{item.localName}}</view>

									</view>

								</view>

							</view>
						</view>

						<view class="bottom-box" style="width: 100%;height: 48rpx;"></view>

					</view>

				</scroll-view>




				<!-- 
				<view class="link-success flex-column-start-center" :style="{'margin-top':102+'rpx'}" v-if="addSuccess">
					<view class="link-success-icon"></view>
					<view class="link-success-text flex-row-center-center">添加成功</view>
				</view> -->

			</view>

		</view>
	</view>
</template>

<script>
	import mBack from "@/components/m-back/index.vue"
	import {
		wechatBindDevice,
		getUserDevice,
		changeDeviceLogin
	} from "@/api/mbti.js"
	import {
		getMbtiSourceByKey
	} from "@/utils/mbti-source.js"
	export default {
		components: {
			mBack
		},
		data() {
			return {
				bgUrl: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/d394a848c52a40a0b7fc9baf22ba6a01.png",
				screenWidth: 375,
				rpxMenuButtonHeight: 64,
				rpxMenuButtonTop: 100,
				contentTop: 300,
				capsuleBottomTop: 300,
				tipSteps: [{
						icon: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/4204fced0bd14bc2b4b0d2bb4aa1d3eb.png",
						text: "请将你的Clackey处于开机状态。",
					},
					{
						icon: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/2e42c87859324d3c9533648820f6cbd2.png",
						text: "请确保你的手机“蓝牙”功能处于开启状态。",
					},
					{
						icon: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/fd1ef9ba4e8b4d15b379a8660861c77e.png",
						text: "在手机蓝牙设置页，蓝牙设备列表中选择“Clackey-…”连接。",
					},
				],
				deviceMacAddress: "",
				deviceList: ["", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
					"", "", "", "", "",
				],
				userDeviceAddress: [],

				userDeviceList: [],
				nowDeviceList: [
					// {
					// 	mbti: "infj",
					// 	mbtiAvatar: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/454367ca87f24b8aba1585a9e485ced8.png",
					// 	name: "MBTI_INFJ_F09E9E048A36",
					// },
					// {
					// 	mbti: "entj",
					// 	mbtiAvatar: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/7daad6622d60443a867951f847e2eb3b.png",
					// 	name: "MBTI_INFJ_F09E9E048A37",
					// },
					// {
					// 	mbti: "infj",
					// 	mbtiAvatar: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/454367ca87f24b8aba1585a9e485ced8.png",
					// 	name: "MBTI_INFJ_F09E9E048A36",
					// },
					// {
					// 	mbti: "entj",
					// 	mbtiAvatar: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/7daad6622d60443a867951f847e2eb3b.png",
					// 	name: "MBTI_INFJ_F09E9E048A37",
					// },
					// {
					// 	mbti: "infj",
					// 	mbtiAvatar: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/454367ca87f24b8aba1585a9e485ced8.png",
					// 	name: "MBTI_INFJ_F09E9E048A36",
					// },
					// {
					// 	mbti: "entj",
					// 	mbtiAvatar: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/7daad6622d60443a867951f847e2eb3b.png",
					// 	name: "MBTI_INFJ_F09E9E048A37",
					// },
					// {
					// 	mbti: "infj",
					// 	mbtiAvatar: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/454367ca87f24b8aba1585a9e485ced8.png",
					// 	name: "MBTI_INFJ_F09E9E048A36",
					// },
					// {
					// 	mbti: "entj",
					// 	mbtiAvatar: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/7daad6622d60443a867951f847e2eb3b.png",
					// 	name: "MBTI_INFJ_F09E9E048A37",
					// },
				],

				addSuccess: false,
				isAddOldDevice: false
			}
		},
		computed: {
			nowDeviceMacList() {
				let arr = this.nowDeviceList.map((item, index) => {
					return item.macAddress
				})

				return arr
			},
			userDeviceMacList() {
				let arr = this.userDeviceList.map((item, index) => {
					return item.macAddress
				})
				console.log("已经有的是", arr)

				return arr
			},

		},
		created() {
			try {
				let screenWidth = uni.getStorageSync('screenWidth')
				if (screenWidth) {
					this.screenWidth = screenWidth
				} else {
					this.screenWidth = uni.getSystemInfoSync().screenWidth; // 当前设备屏幕宽度
					uni.setStorageSync("screenWidth", this.screenWidth)
				}
				let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
				let {
					top,
					height
				} = menuButtonInfo

				let rpxHeight = this.pxToRpx(height)
				let rpxTop = this.pxToRpx(top)
				this.rpxMenuButtonHeight = rpxHeight
				this.rpxMenuButtonTop = rpxTop

				this.contentTop = rpxTop + rpxHeight + 98
				this.capsuleBottomTop = rpxTop + rpxHeight

			} catch (error) {
				//TODO handle the exception
			}
		},
		async onLoad() {
			console.log("初始化");
			// return
			await this.handleGetUserDevice()
			this.handleStartDiscovery()
		},
		onUnload() {
			this.handleCloseAll()
		},
		onShow() {
			console.log("展示", this.addSuccess);
			if (this.addSuccess) {
				uni.reLaunch({
					url: "/pages/game/play/index"
				})
			}
		},
		methods: {
			pxToRpx(px) {
				const designWidth = 750; // 设计稿宽度
				const rpx = (designWidth / this.screenWidth) * px; // 根据屏幕宽度计算 rpx
				return rpx;
			},
			extractType(str) {
				const parts = str.split('_'); // 用下划线分割字符串[1,4](@ref)
				if (parts.length >= 3) {
					return parts[1].toLowerCase(); // 取第二个元素并转小写[2,5](@ref)
				}
				return ''; // 处理异常情况
			},
			handleBack() {
				uni.navigateBack()
			},
			handleChangeAddType() {
				this.isAddOldDevice = !this.isAddOldDevice
			},
			async handleGetUserDevice() {
				let res = await getUserDevice()
				let list = null
				try {
					list = res.data.data
				} catch {

				}
				if (!list) {
					return
				}
				this.userDeviceList = [...list]
				console.log("获取到用户的list是", res)
				console.log("获取到用户的list是111", this.userDeviceList)
				// this.userDeviceAddress = [...list].map((item, index) => {
				// 	return item.macAddress
				// })

			},
			handleCloseAll() {
				this.handleStopDiscovery()
				uni.closeBluetoothAdapter();
				uni.offBluetoothDeviceFound();
				this.nowDeviceList = []
				this.userDeviceList = []

			},
			handleStopDiscovery() {
				uni.stopBluetoothDevicesDiscovery();
			},
			uniqueByName(arr) {
				const seen = new Map();
				return arr.filter(item => {
					// 当name不存在或已存在时返回false，否则存入Map
					return item.name && !seen.has(item.name) && seen.set(item.name, 1)
				});
			},
			handleStartDiscovery() {
				uni.openBluetoothAdapter({
					success: (res) => {
						uni.startBluetoothDevicesDiscovery({
							allowDuplicatesKey: true,
							interval: 200,
						});

						uni.onBluetoothDeviceFound(data => {
							let list = []
							list = [...data.devices].filter((item, index) => {
								return (String(item.name).includes("MBTI"))
							}).map((item, index) => {
								let mbtiAvatar = ""
								let macAddress = this.formatString(item.localName)
								let mbtiKey = this.extractType(item.localName)
								if (mbtiKey) {
									let source = getMbtiSourceByKey(mbtiKey)
									if (source) {
										mbtiAvatar = source.smallAvatar
									}
								}
								return {
									...item,
									mbtiAvatar,
									macAddress
								}


							})
							list = this.uniqueByName(list)
							list.forEach((item, index) => {
								if (!this.nowDeviceMacList.includes(item.macAddress) && !this
									.userDeviceMacList.includes(item.macAddress)) {
									this.nowDeviceList.push(item)
								}
							})
							console.log("当前的列表是", this.nowDeviceList)

							// this.deviceList = list

						});
					},
					fail: (err) => {
						uni.showToast({
							title: "请先打开手机蓝牙",
							icon: "none"
						})
					}
				})







			},
			formatString(str) {
				// 提取下划线后的部分，并立即转小写
				const afterUnderscore = (str.split('_').pop() || '').toLowerCase();

				// 每两位分割并插入冒号
				return afterUnderscore.match(/.{2}/g)?.join(':') || '';
			},
			handleChangeDeviceLogin(deviceId) {
				changeDeviceLogin(deviceId).then(res => {
					// uni.showToast({
					// 	title: "添加成功~",
					// 	icon: "none"
					// })
					setTimeout(() => {
						uni.navigateTo({
							url: "/pages/mbti/mbti-device-detail"
						})
					}, 1000)

				})
			},
			handleNewDeviceClick(item, index) {
				uni.showLoading({
					title: "设备添加中~",
					icon: "none"
				})
				let macAddress = this.formatString(item.localName)

				if (macAddress) {
					console.log("传入的设备Id", macAddress)
					wechatBindDevice(macAddress).then(res => {
						console.log("绑定返回", res)
						if (res.data.code == 500) {
							uni.showToast({
								title: res.data.msg,
								icon: "none"
							})
							uni.hideLoading()
							return
						}
						uni.hideLoading()
						this.handleCloseAll()
						this.addSuccess = true
						uni.showToast({
							title: "添加成功~",
							icon: "none"
						})
						// 过滤掉当前名称
						this.nowDeviceList = this.nowDeviceList.filter((citem, cindex) => {
							return citem.name != item.name
						})
						this.nowDeviceList = []
						console.log("绑定成功的返回", res)

						// handleChangeDeviceLogin

						getUserDevice().then(res => {
							let list = null
							try {
								list = res.data.data
							} catch (error) {
								//TODO handle the exception
							}
							if (!list) {
								uni.showToast({
									title: "服务端异常~",
									icon: "none"
								})
								return
							}
							console.log('成功拿到的列表是', list, macAddress)
							let obj = [...list].find((citem, cindex) => {
								return citem.macAddress == macAddress
							})

							// 添加成功
							if (obj) {
								this.handleChangeDeviceLogin(obj.id)
							} else {
								uni.showToast({
									title: "添加失败~",
									icon: "none"
								})
							}

						})




					}).catch((err) => {
						console.log("绑定失败的返回", err)
						uni.showToast({
							title: "设备绑定失败",
							icon: "none"
						})
					})
				}
			},
			handleWechatBindDevice() {
				if (this.deviceMacAddress) {
					wechatBindDevice(this.deviceMacAddress).then(res => {
						uni.showToast({
							title: "设备绑定成功",
							icon: "none"
						})

						// 添加成功，先切换添加成功的设备为当前设备，跳转设备详情

					}).catch((err) => {
						uni.showToast({
							title: "设备绑定失败",
							icon: "none"
						})
					})
				}
			},
			handleGetCanLinkDeviceList() {
				// 过滤出没有被绑定的设备，点击设备列表中的项，进行绑定
			}
		}
	}
</script>

<style lang="scss" scoped>
	.mbti-groups {
		position: absolute;
		left: 0rpx;
		top: 0rpx;
		width: 100%;
		height: 100%;
		background-color: #ededed;
		box-sizing: border-box;

		.mbti-groups-content {
			width: 100%;
			height: 100%;
			background-repeat: no-repeat;
			background-size: cover;
			background-position: center center;

			.top-box {
				width: 100%;
			}

			.content-box {
				position: relative;
				width: 100%;
				flex: 1;
				overflow: hidden;


				.discover-box {
					width: 100%;
					// height: 100%;
					z-index: 1;

					.tip-title {
						position: relative;
						width: 100%;
						height: 56rpx;
						font-weight: 500;
						font-size: 40rpx;
						color: #153135;
						line-height: 56rpx;
						padding: 0 48rpx;
						margin-bottom: 44rpx;

						.change-add-type {
							position: absolute;
							right: 48rpx;
							top: 50%;
							transform: translateY(-50%);
							color: #979797;
							font-size: 28rpx;
							line-height: 28rpx;

						}
					}

					.tip-sub-title {
						width: 100%;
						height: 44rpx;
						font-weight: 300;
						font-size: 32rpx;
						color: #494949;
						line-height: 44rpx;
						padding: 0 48rpx;
						margin-bottom: 16rpx;

						.switch-icon {
							width: 36rpx;
							height: 36rpx;
							margin-left: 4rpx;
						}
					}

					.last-sub-title {
						margin-bottom: 148rpx;
					}

					.discover-blue-searching {
						width: 100%;
						height: 356rpx;
						margin-bottom: 128rpx;

						.discover-blue-icon {
							width: 268rpx;
							height: 268rpx;
							margin-bottom: 44rpx;

							.discover-blue-center {
								position: relative;
								width: 132rpx;
								height: 132rpx;

								.discover-blue-center-content {
									position: absolute;
									left: 50%;
									top: 50%;
									transform: translate(-50%, -50%);
									width: 132rpx;
									height: 132rpx;
									border-radius: 50%;
									background: #99C26D;
									z-index: 9;

									.discover-blue-center-icon {
										width: 40rpx;
										height: 48rpx;
									}
								}


								.blue-child {
									position: absolute;
									left: 50%;
									top: 50%;
									width: 100%;
									height: 100%;
									background: #99C26D;
									border-radius: 50%;
									opacity: 0;
									transform: translate(-50%, -50%);
									animation: searching 3s linear infinite;
									z-index: 1;

								}

								.blue-child-two {
									z-index: 2;
									animation-delay: 1s;
								}

								.blue-child-three {
									z-index: 3;
									animation-delay: 2s;
								}
							}
						}

						@keyframes searching {
							0% {
								transform: translate(-50%, -50%) scale(1);
								opacity: 0.2;
							}

							100% {
								transform: translate(-50%, -50%) scale(3);
								opacity: 0;
							}
						}

						.discover-blue-tip {
							width: 100%;
							height: 44rpx;
							font-weight: 300;
							font-size: 32rpx;
							color: #979797;
							line-height: 44rpx;
							text-align: center;
						}
					}

					.device-list-box {
						width: 100%;
						// height: 400rpx;

						.device-list-tip {
							width: 100%;
							height: 40rpx;
							font-weight: 400;
							font-size: 28rpx;
							color: #494949;
							line-height: 40rpx;
							padding: 0rpx 48rpx;
							margin-bottom: 24rpx;
						}

					}

				}

				.device-list {
					width: 100%;
					height: 100%;
					// overflow: hidden;
					padding: 0rpx 48rpx;
					border-radius: 20rpx;

					.device-list-content {
						width: 100%;
						background-color: #fff;
						border-radius: 20rpx;
						// overflow: hidden;


						.device-item {
							width: 100%;
							height: 120rpx;
							padding: 0rpx 28rpx;

							.device-avatar {
								width: 48rpx;
								height: 48rpx;
								margin-right: 16rpx;
							}

							.device-name {
								position: relative;
								flex: 1;
								// height: 44rpx;
								height: 100%;
								font-weight: 400;
								font-size: 32rpx;
								color: #979797;
								line-height: 44rpx;

								&::after {
									content: "";
									position: absolute;
									left: 0rpx;
									bottom: 0rpx;
									width: 100%;
									height: 0.5rpx;
									background-color: #ebebeb;
								}
							}

							&:last-child {
								.device-name {
									&::after {
										opacity: 0;
									}
								}
							}

						}

					}
				}

				.link-success {
					width: 100%;
					padding: 0rpx 48rpx;

					.link-success-icon {
						width: 300rpx;
						height: 300rpx;
						margin-bottom: 56rpx;
						background: #D8D8D8;
						border: 2rpx solid #979797;
					}

					.link-success-text {
						width: 100%;
						height: 56rpx;
						font-weight: 300;
						font-size: 40rpx;
						color: #153135;
						line-height: 56rpx
					}

				}


			}
		}

	}
</style>